package com.soul.admin.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import com.soul.admin.mapper.AnalysisMapper;
import com.soul.admin.mapper.LogMapper;
import com.soul.model.db.Analysis;
import com.soul.model.vo.AnalysisSummaryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author mdoya
 * @version 1.0
 * @description: 定时任务业务执行者
 */
@Slf4j
@Service
public class AnalysisService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisMapper analysisMapper;

    /**
     *  执行者  -  统计报表
     */
    public void analysis() {
        log.debug("定时任务执行者开始统计报表工作");
        // 今天日期
        String today = DateUtil.today();
        // 昨天日期
        DateTime dateTime = DateUtil.yesterday();
        String yesterday = DateUtil.format(dateTime, "yyyy-MM-dd");

        // 1. 查询日统计报告记录
        Analysis analysis = analysisMapper.findByRecordDate(today);
        // 2. 更新日报表记录
        if (analysis != null){
            analysis.setNumRegistered(logMapper.countNumRegisteredToday(today)); // 统计今天新注册用户数
            analysis.setNumActive(logMapper.countNumActiveByDate(today)); // 统计今天活跃用户数
            analysis.setNumLogin(logMapper.countNumLoginByDate(today)); // 统计今天登陆次数
            analysis.setNumRetention1d(logMapper.countNumRetention1d(today,yesterday)); // 统计次日留存用户数
            analysisMapper.updateById(analysis);
            return;
        }
        // 3. 新增日报表记录
        analysis = new Analysis();
        DateTime date = DateUtil.parse(today, "yyyy-MM-dd");
        analysis.setRecordDate(date);
        analysis.setNumRegistered(logMapper.countNumRegisteredToday(today)); // 统计今天新注册用户数
        analysis.setNumActive(logMapper.countNumActiveByDate(today)); // 统计今天活跃用户数
        analysis.setNumLogin(logMapper.countNumLoginByDate(today)); // 统计今天登陆次数
        analysis.setNumRetention1d(logMapper.countNumRetention1d(today,yesterday)); // 统计次日留存用户数
        analysisMapper.insert(analysis);

        log.debug("定时任务执行者结束统计报表工作");
    }

    public AnalysisSummaryVo summary() {
        // 今天日期
        String today = DateUtil.today();
        DateTime dateTime = DateUtil.parse(today, "yyyy-MM-dd");
        AnalysisSummaryVo analysisSummaryVo = new AnalysisSummaryVo();
        // 累计用户数 cumulativeUsers
        analysisSummaryVo.setCumulativeUsers(analysisMapper.totalUser());
        // 过去30天活跃用户数 activePassMonth
        analysisSummaryVo.setActivePassMonth(analysisMapper.countActive(DateUtil.offsetDay(dateTime,-30)));
        // 过去7天活跃用户 activePassWeek
        analysisSummaryVo.setActivePassWeek(analysisMapper.countActive(DateUtil.offsetDay(dateTime,-7)));


        // 今日新增用户数量 newUsersToday
        Long todayCountNewUsers = analysisMapper.countNewUsers(today);
        analysisSummaryVo.setNewUsersToday(todayCountNewUsers);
        Long yesterdayCountNewUsers = analysisMapper.countNewUsers(today);
        // 今日新增用户涨跌率，单位百分数，正数为涨，负数为跌 newUsersTodayRate
        analysisSummaryVo.setNewUsersTodayRate(computeRate(todayCountNewUsers,yesterdayCountNewUsers));


        // 今日登录次数 loginTimesToday
        Long todayCountLoginTimes = analysisMapper.countLoginTimes(today);
        analysisSummaryVo.setLoginTimesToday(todayCountLoginTimes);
        Long yesterdayCountLoginTimes = analysisMapper.countLoginTimes(today);
        // 今日登录次数涨跌率，单位百分数，正数为涨，负数为跌 loginTimesTodayRate
        analysisSummaryVo.setLoginTimesTodayRate(computeRate(todayCountLoginTimes,yesterdayCountLoginTimes));


        // 今日活跃用户数量 activeUsersToday
        Long todayCountActiveUsers = analysisMapper.countActiveUsers(today);
        analysisSummaryVo.setActiveUsersToday(todayCountActiveUsers);
        Long yesterdayCountActiveUsers = analysisMapper.countActiveUsers(today);
        // 今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌 activeUsersTodayRate
        analysisSummaryVo.setActiveUsersTodayRate(computeRate(todayCountActiveUsers,yesterdayCountActiveUsers));

        return analysisSummaryVo;
    }

    /**
     * 传入当前时间 上一次时间
     * @param current
     * @param last
     * @return
     */
    private static BigDecimal computeRate(Long current, Long last) {
        BigDecimal result;
        if (last == 0) {
            // 当上一期计数为零时，此时环比增长为倍数增长
            result = new BigDecimal((current - last) * 100);
        } else {
            result = BigDecimal.valueOf((current - last) * 100).divide(BigDecimal.valueOf(last), 2, BigDecimal.ROUND_HALF_DOWN);
        }
        return result;
    }
}
